
const tmplBase ='<div class="ximage" style="display: none"><img /></div>';

export default class xImage{
    $root;
    $myImg;
    constructor() {
        this.$root =  $(tmplBase);
        $('body').append(this.$root);
        this.$myImg = this.$root.find("img");

        //点击淡出消失弹出层
        this.$root.click(function(){
            $(this).fadeOut();
        });
    };

    static getInstance() {
        if(!xImage.instance) {
            xImage.instance = new xImage();
        }
        return xImage.instance;
    }

    static pop($img){
        xImage.getInstance().show($img);
    }

    show($img){
        let src = typeof $img=='string' ? $img:$img.attr("src");
        //获取浏览器的宽度
        let _w = parseInt($(window).width());
        let _h = parseInt($(window).height());
        let realWidth;
        let realHeight;
        let _this = this;
        _this.$myImg.attr("src", src).load(function(){

            realWidth = this.width;
            realHeight = this.height;

            // 缩放比例
            let _h_rate = realHeight / _h , _w_rate = realWidth /_w ;
            if(_w_rate>_h_rate){
                if(_w_rate>1){
                    _this.$myImg.css("width","100%").css("height","auto");
                    _this.$myImg.css("top",(_h - realHeight/_w_rate)/2+"px");
                    _this.$myImg.css("left",0);
                }else{
                    _this.$myImg.css("width",realWidth+'px').css("height",realHeight+'px');
                    _this.$myImg.css("top",(_h - realHeight)/2+"px");
                    _this.$myImg.css("left",(_w - realWidth)/2+"px");
                }
            }else{
                if(_h_rate>1){
                    _this.$myImg.css("height","100%").css("width","auto");
                    _this.$myImg.css("top",0);
                    _this.$myImg.css("left",(_w - realWidth/_h_rate)/2+"px");
                }else{
                    _this.$myImg.css("width",realWidth+'px').css("height",realHeight+'px');
                    _this.$myImg.css("top",(_h - realHeight)/2+"px");
                    _this.$myImg.css("left",(_w - realWidth)/2+"px");
                }
            }
            _this.$root.fadeIn();
        });

    };



}